package com.knight.base;

import java.lang.reflect.Field;

/**
 * ClassLoader和Class.forName的区别 :
 * Java中Class.forName和classloader都可以用来对类进行加载。
 * Class.forName除了将类的.class文件加载到jvm中之外，还会对类进行解释，执行类中的static块。
 * 而classloader只干一件事情，就是将.class文件加载到jvm中，不会执行static中的内容，只有在newInstance才会去执行static块。
 * Class.forName(name,initialize,loader)带参数也可控制是否加载static块。并且只有调用了newInstance()方法采用调用构造函数，创建类的对象。
 * @param args
 */
public class ClassLoaderAndForNameTest {

	public static void main(String[] args) {
		String wholeNameLine = "com.knight.base.Line";
		String wholeNamePoint = "com.knight.base.Point";

		System.out.println("classloader testing...");
		testClassLoader(wholeNameLine, wholeNamePoint);
		System.out.println("---------------------------------------");
		System.out.println("Class.forName testing...");
		testForName(wholeNameLine, wholeNamePoint);
	}

	// classloader
	public static void testClassLoader(String wholeNameLine, String wholeNamePoint) {
		ClassLoader loader = ClassLoader.getSystemClassLoader();
		Class<?> line;
		Class<?> point;
		try {
			line = loader.loadClass(wholeNameLine);
			point = loader.loadClass(wholeNamePoint);
			System.out.println("line " + line.getName());
			System.out.println("point " + point.getName());
			
//			Field[] fields = line.getDeclaredFields();
//			for (int i = 0; i < fields.length; i++) {
//				Field field = fields[i];
//				System.out.println(field.get);
//			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// Class.forName
	@SuppressWarnings("rawtypes")
	public static void testForName(String wholeNameLine, String wholeNamePoint) {
		try {
			Class line = Class.forName(wholeNameLine);
			Class point = Class.forName(wholeNamePoint);
			System.out.println("line " + line.getName());
			System.out.println("point " + point.getName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
